package timgmbh.monopoly.services;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Hashtable;

import timgmbh.monopoly.general.Config;

public class DatabaseService {
	
	//********************************************************************************************************************
	//********************************************************************************************************************
	//********************************************************************************************************************
	// DECLARATION
	
	private static Connection conn;				//JDBC connection instance
	
	//private static Boolean success;				//last execution failed?
	//private static long lastKey;				//for INSERT
	
	//********************************************************************************************************************
	//********************************************************************************************************************
	//********************************************************************************************************************
	// INITIALIZE
	
	public static void init() throws Exception {
		
		  //Open Connection
	      try {
		      Class.forName(Config.DB_DRIVER);
		      conn = DriverManager.getConnection(Config.DB_DATABASE_URL + ";SCHEMA=" + Config.DB_SCHEMA, Config.DB_USER, Config.DB_PASS);
	      } catch (Exception e) {
	    	  System.out.println("Error: " + e.getClass() + ": " + e.getMessage());
	    	  throw new Exception("Database Connection Error");
	      }
	      
	      //Some initializations
	      /*success = true;
	      lastKey = -1;*/
	}
	
	public static void close() {
		//Closes the connection
		try {
			conn.close();
		} catch (Exception e) {
			
		}
	}
	
	//********************************************************************************************************************
	//********************************************************************************************************************
	//********************************************************************************************************************
	// METHOD: query
	// RETURN: ResultSet or NULL (if there is no result or if there is an error)
	
	/*public static ResultSet queryUnsafe(String sqlCode) {
		
		//debug log
		if (Config.DEBUG_DATABASE == true) System.out.println("Sending unsafe SQL Statement: " + sqlCode);
		
		try {
			PreparedStatement statement = conn.prepareStatement(sqlCode);					//create new statement instance
			statement.execute();															//execute code
			
			success = true;																	//no exception? must have been successful! :)
			ResultSet keys = statement.getGeneratedKeys();									//receive primarykey resultset
			if (!keys.next()) {
				lastKey = -1;																//no primarykey
			} else {
				lastKey = keys.getLong(1);													//store primarykey
			}
			
			ResultSet res = statement.getResultSet(); 
			//statement.close();
			
			return res;																		//return result (may be null)
		} catch (Exception e) {
			System.out.println("Error: " + e.getClass() + ": " + e.getMessage());		//error? add report to internal ArrayList
			success = false;
			return null;																	//do not return a result
		}
	}*/
	
	//********************************************************************************************************************
	//********************************************************************************************************************
	//********************************************************************************************************************
	// HANDLE ERRORS

	/*public static boolean wasSuccessful() {
		//returns whether last statement was successful
		return success;	
	}*/
	
	//********************************************************************************************************************
	//********************************************************************************************************************
	//********************************************************************************************************************
	// GETTER
	
	/*public static long getInsertedId() {
		//returns lastkey
		return lastKey;
	}*/
	
	public static Hashtable<String, String> getTableColumns(String table) {
		//creates new hashtable 
		Hashtable<String, String> columns = new Hashtable<String, String>();
		
		try {
			//gets metadata from database
			DatabaseMetaData met = conn.getMetaData();
			ResultSet res = met.getColumns(Config.DB_CATALOG, Config.DB_SCHEMA, table.toUpperCase(), null);
			
			//Reads data from data set
			while (res.next()) {
				columns.put(res.getString("COLUMN_NAME"), res.getString("TYPE_NAME"));
			}
			
			//returns hashtable
			return columns;
		} catch (Exception e) {
			//returns null if exception occurred
			return null;
		}
	}
	
	//********************************************************************************************************************
	//********************************************************************************************************************
	//********************************************************************************************************************
	// GENERAL PUBLICS
	
	public static String getPlaceholders(int number) {
		String placeholders = "";
		for (int i=1;i<number;i++) {
			if (i != 1) placeholders = placeholders + ", ";
			placeholders = placeholders + "?";
		}
		return placeholders;
	}
	
	public static Connection getConn() {
		return conn;
	}
}